<?php
/**
 * @file
 * Download Monitor - Allows you to trace file downloads. Just place the direct link
 * to the file on the web, and specify the extensions of files you want to trace in the GUI.
 * It creates interactive chart and records downloads for today, yesterday, this week,
 * last week, this month, last month and total.
 * Requires writable .htaccess file of Apache Web server in Joomla root folder.
 * @package download-monitor
 * @version 1.0
 * @revision @REVISION@
 * @license http://www.gnu.org/licenses/gpl-3.0.txt     GNU General Public License v3
 * @copyright (C) 2012 by CodeGravity.com - All rights reserved!
 * @website http://www.codegravity.com
 */

defined('_JEXEC') or die;
$db =& JFactory::getDBO();

$task="";
if (@isset($_REQUEST["task"]))
{
    $task=trim(@$_REQUEST["task"]);
}

$eid="";
if (@isset($_REQUEST["eid"]))
{
    $eid=trim(@$_REQUEST["eid"]);
}

$did="";
if (@isset($_REQUEST["did"]))
{
    $did=trim(@$_REQUEST["did"]);
}

$extensionquery = sprintf("SELECT * FROM #__download_monitor_extension");
$db->setQuery($extensionquery);
$extensionar = $db->loadRowList();

$filepathquery = sprintf("SELECT * FROM #__download_monitor_paths");
$db->setQuery($filepathquery);
$filepathar = $db->loadRowList();

$month = date("m");
$week = date("N");
$curryear = date("Y");
$currmonth = date("Y-m");
$currdate = date("Y-m-d");

$yesterday = date("Y-m-d", (strtotime($currdate)-(60*60*24)));
$currmonthday = $currmonth. "-01";
$lmonth = $month - 1;
if($lmonth == 0)
{
    $lmonth = 12;
    $curryear = $curryear-1;
}
$lastmonth =$curryear."-".$lmonth."-01";
$weekday = date("Y-m-d", (strtotime($currdate)-($week*60*60*24)));
$lweekday = date("Y-m-d", (strtotime($weekday)-(7*60*60*24)));

if (isset($_GET['del']) && trim($_GET['del'])=="del")
{
    $co = trim($_GET['co']);

    $extensionquery_ht_prev = sprintf("SELECT * FROM #__download_monitor_extension");
    $db->setQuery($extensionquery_ht_prev);
    $extensionar_ht_prev = $db->loadRowList();

    foreach($extensionar_ht_prev as $extensionhtprev)
    {
        $ext_n_prev = $ext_n_prev.$extensionhtprev[1]."|";
    }
    $ext_n_prev = substr($ext_n_prev,0,strlen($ext_n_prev)-1);



    $extensionquery_del = sprintf("delete from #__download_monitor_extension where eid='%d'", (int) $co);
    $db->setQuery($extensionquery_del);
    $db->query();
    $extensionquery_ht = sprintf("SELECT * FROM #__download_monitor_extension");
    $db->setQuery($extensionquery_ht);
    $extensionar_ht = $db->loadRowList();

    foreach($extensionar_ht as $extensionht)
    {
        $ext_n = $ext_n.$extensionht[1]."|";
    }
    $ext_n = substr($ext_n,0,strlen($ext_n)-1);

    $findpath = (JURI::root());
    $p = parse_url( $findpath );
    $path = $p['path'];

    $writingonht_prev = "RewriteEngine on"."\n"."RewriteRule ^(.*).(".$ext_n_prev.")$ ".$path."index.php?option=com_download-monitor&file=$1.$2 [R,L]";

    $jp = str_replace("administrator","",JPATH_BASE);

    $root_file = $jp.".htaccess";

    $existingcode = file_get_contents($root_file);

    $existingcode_f = str_replace($writingonht_prev,"",$existingcode);
    //$existingcode_f = str_replace($writingonht_prev1,"",$existingcode);

    $writingonht = $existingcode_f."RewriteEngine on";
    $writingonht = $writingonht."\n"."RewriteRule ^(.*).(".$ext_n.")$ ".$path."index.php?option=com_download-monitor&file=$1.$2 [R,L]";

    if (file_exists($root_file))
    {
        if (is_writable($root_file))
        {
            if($ext_n!="")
            {
                $handle = fopen($root_file,"w");
                fwrite($handle,$writingonht);
                fclose($handle);
                header("location: index.php?option=com_download-monitor");
            }
        }
        else
        {
            $handle = fopen($root_file,"w");
            fwrite($handle,$existingcode_f);
            fclose($handle);
            header("location: index.php?option=com_monitor");
        }
    }
    else
    {
        $handle = fopen($root_file,"w");
        if ($handle)
        {
            fwrite($handle,$writingonht);
            fclose($handle);
            header("location: index.php?option=com_download-monitor");
        }
        else
        {
            echo ".htaccess could not be created, Please create your own.";
        }
    }

}

if (isset($_GET['del']) && trim($_GET['del'])=="del_filepath")
{
    $co = trim($_GET['co']);
    $extensionquery_del = sprintf("delete from #__download_monitor_paths where did='%d'", (int)$co);
    $db->setQuery($extensionquery_del);
    $db->query();

    header("location: index.php?option=com_download-monitor");
}

?>

<html>
<head>
    <title>Member Management</title>
    <link href="components/com_download-monitor/views/monitors/tmpl/styles/myCss.css" rel="stylesheet" type="text/css">
    <link rel="stylesheet" href="components/com_download-monitor/views/monitors/tmpl/styles/style.css" type="text/css" media="print, projection, screen" />
    <script type="text/javascript" src="components/com_download-monitor/views/monitors/tmpl/js/jquery-latest.js"></script>
    <script type="text/javascript" src="components/com_download-monitor/views/monitors/tmpl/js/jquery.tablesorter.js"></script>
    <script type='text/javascript' src='https://www.google.com/jsapi'></script>

    <script type="text/javascript">
        google.load("visualization", "1", {packages:["corechart"]});
        google.setOnLoadCallback(drawChart);
        function drawChart()
        {
            var data = google.visualization.arrayToDataTable([
            <?php include("data.php");?>

            ]);
            var options = {
                title: 'Total Download'
            };
            var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
            chart.draw(data, options);
        }

        $(document).ready(function()
            {
                $("#myTable").tablesorter();
            }
        );

        function check_add()
        {
            var strErr,field;
            strErr="";
            if (document.addform.extname.value=="")
            {
                strErr+="*Enter Name \n";
                if (typeof(field)=="undefined")
                {
                    field=document.addform.extname;
                }
            }
            if(strErr!="")
            {
                alert("The required Information is incomplete\n\n"+strErr);
                field.focus();
                return false;
            }
        }

        function check_edit()
        {
            var strErr,field;
            strErr="";
            if (document.editform.extname.value=="")
            {
                strErr+="*Enter Name \n";
                if (typeof(field)=="undefined")
                {
                    field=document.editform.extname;
                }
            }
            if(strErr!="")
            {
                alert("The required Information is incomplete\n\n"+strErr);
                field.focus();
                return false;
            }
        }
        function check_edit_filepath()
        {
            var strErr,field;
            strErr="";
            if (document.editfilepathform.filepathname.value=="")
            {
                strErr+="*Enter Name \n";
                if (typeof(field)=="undefined")
                {
                    field=document.editfilepathform.filepathname;
                }
            }
            if(strErr!="")
            {
                alert("The required Information is incomplete\n\n"+strErr);
                field.focus();
                return false;
            }
        }
        function check_add_filepath()
        {
            var strErr,field;
            strErr="";
            if (document.addfilepathform.filepathname.value=="")
            {
                strErr+="*Enter Name \n";
                if (typeof(field)=="undefined")
                {
                    field=document.addfilepathform.filepathname;
                }
            }
            if(strErr!="")
            {
                alert("The required Information is incomplete\n\n"+strErr);
                field.focus();
                return false;
            }
        }



        function confirmChoice(j)
        {
            msgQuestion = "Confirm Delete!";
            userResponse = confirm(msgQuestion);
            if (userResponse == 1)
            {
                location = "index.php?option=com_download-monitor&del=del&co="+j;
            }
            else
            {
                return;
            }
        }
        function confirmChoicefilepath(j)
        {
            msgQuestion = "Confirm Delete!";
            userResponse = confirm(msgQuestion);
            if (userResponse == 1)
            {
                location = "index.php?option=com_download-monitor&del=del_filepath&co="+j;
            }
            else
            {
                return;
            }
        }

    </script>
</head>
<body bgcolor="#FFFFFF" leftmargin="0" topmargin="0" marginwidth="0" marginheight="0">
<br />
<?php include("edit_ext.php");?>
<?php include("add_ext.php");?>
<?php include("edit_filepath.php");?>
<?php include("add_filepath.php");?>
<?php
if($task=='')
{
    ?>
<div class="heading">Download Monitor </div>

<body>
<div id="chart_div" style="width: 900px; height: 400px;"></div>
</body>

<table width="90%" border="0" align="center" class="table-border">
    <tr>
        <td align="center">
            <?php include("table_statistics.php");?>
        </td>
    </tr>
</table>
<br />
<br />

<table width="90%" border="0" align="center" class="table-border">
    <tr>
        <td align="center">
            <table width="95%" border="0" align="center" cellpadding="3" cellspacing="0">
                <tr>
                    <td height="23" align="left"><b>Extensions Being Monitored</b></td>
                </tr>
                <tr>
                    <td class="" height="23" width="73%" align="left"><div align="right"><a href="index.php?option=com_download-monitor&task=add">Add New Extension</a> </div></td>
                </tr>
                <tr>
                    <td class="" height="23" width="73%" align="left">&nbsp;</td>
                </tr>

            </table>
            <?php include("table_filepath.php");?>
            <br><br>
            <table width="95%" border="0" align="center" cellpadding="3" cellspacing="0">
                <tr>
                    <td height="23" align="left"><b>Files/Paths Being Monitored </b></td>
                </tr>
                <tr>
                    <td class="" height="23" width="73%" align="left"><div align="right"><a href="index.php?option=com_download-monitor&task=add_file">Add New File/Path</a> </div></td>
                </tr>
                <tr>
                    <td class="" height="23" width="73%" align="left">&nbsp;</td>
                </tr>

            </table>
            <?php include("table_extensions.php");?>
            <br />
        </td>
    </tr>
</table>
    <?php
}
?>
<br />
<br />
<br />
</body>
</html>
